import React, { Component } from 'react'
import { isEqual } from 'loadsh'
import classNames from 'classnames'
import GraphCardBody from './graphCardBody'
import Loading from '@/components/loading'
import EmptyData from '@/components/emptyData'
import { asyncComponent } from '@/helpers/asyncComponent'
import styles from './style.module.less'

class CardBody extends Component {
  state = {
    InnerComponent: null,
    cardType: ''
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    if (!isEqual(nextProps.cardType, prevState.cardType) && !nextProps.useBody) {
      const { cardModule, cardType, cardPath, hasPermission, echarts } = nextProps
      let InnerComponent = null
      if (hasPermission) {
        InnerComponent = echarts
          ? GraphCardBody
          : asyncComponent(
              import(/* webpackChunkName: "cards" */ `@/modules/${cardModule}/${cardType}`)
            )
      } else {
        InnerComponent = () => <EmptyData type="permission" size="sm" />
      }
      return {
        InnerComponent,
        cardType
      }
    }
    return null
  }

  shouldComponentUpdate(nextProps, nextState) {
    return !isEqual(this.props, nextProps) || !isEqual(this.state, nextState)
  }

  render() {
    const { InnerComponent } = this.state
    const {
      filters,
      settings,
      setFilters,
      loading,
      isLoading,
      isEmpty,
      hideHeader,
      cardBodyClassName,
      openLoading,
      closeLoading,
      renderEmptyData,
      echarts,
      echartsLoading,
      echartsData,
      openGraphStatus,
      zoomShow,
      toggleCollapseShow,
      toggleZoomShow,
      getLoadingState
    } = this.props
    return (
      <div
        className={classNames(
          styles.cardBody,
          cardBodyClassName,
          hideHeader && styles.noHeaderBody
        )}>
        {(isLoading || echartsLoading) && (
          <div className={styles.isLoading}>
            <Loading size="md" />
          </div>
        )}
        {isEmpty && (
          <div className={styles.isEmpty}>
            <EmptyData size={zoomShow ? 'lg' : 'sm'} />
          </div>
        )}
        {InnerComponent ? (
          <InnerComponent
            openLoading={openLoading}
            closeLoading={closeLoading}
            loading={loading}
            isEmpty={isEmpty}
            renderEmptyData={renderEmptyData}
            filters={filters}
            settings={settings}
            setFilters={setFilters}
            echarts={echarts}
            echartsData={echartsData}
            openGraphStatus={openGraphStatus}
            zoomShow={zoomShow}
            toggleCollapseShow={toggleCollapseShow}
            toggleZoomShow={toggleZoomShow}
            getLoadingState={getLoadingState}
          />
        ) : null}
      </div>
    )
  }
}

export default CardBody
